package com.cqh.recruit.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqh.recruit.mapper.ActivityCheckMapper;
import com.cqh.recruit.mapper.ActivityMapper;
import com.cqh.recruit.pojo.dto.ActivityQueryDto;
import com.cqh.recruit.pojo.dto.StudentActivityQueryDTO;
import com.cqh.recruit.pojo.entity.Activity;
import com.cqh.recruit.pojo.entity.ActivityCheck;
import com.cqh.recruit.pojo.vo.ActivityListVo;
import com.cqh.recruit.pojo.vo.StudentActivityListVO;
import com.cqh.recruit.result.Result;
import com.cqh.recruit.service.IActivityService;
import com.cqh.recruit.utils.StudentThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 活动信息表 服务实现类
 * </p>
 *
 * @author dh
 * @since 2025-10-18
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityCheckMapper activityCheckMapper;

    @Override
    public Page<ActivityListVo> findActivityByQueryDto(ActivityQueryDto activityQueryDto) {
        Page page = new Page(activityQueryDto.getPage(), activityQueryDto.getLimit());
        return getBaseMapper().findActivityByQueryDto(page, activityQueryDto);
    }

    @Override
    public ActivityListVo findActivityById(Long id) {
        return activityMapper.findActivityById(id);
    }

    /**
     * 根据查询条件分页查询活动列表
     */
    @Override
    public Page<StudentActivityListVO> queryActivityList(StudentActivityQueryDTO queryDto) {
        Page<StudentActivityListVO> page = new Page<>(queryDto.getPage(), queryDto.getLimit());
        return getBaseMapper().queryActivityList(page, queryDto);

    }

    /**
     * 查询登陆学生已报名的活动列表
     */
    @Override
    public Page<StudentActivityListVO> queryEnrolledActivityList(StudentActivityQueryDTO queryDto) {
        //获取当前登录学生id
        Long stuId = StudentThreadLocal.get().getId();
        Page<StudentActivityListVO> page = new Page<>(queryDto.getPage(), queryDto.getLimit());
        return getBaseMapper().queryEnrolledActivityList(page, queryDto, stuId);
    }

    /**
     * 活动报名
     */
    @Override
    public Result applyActivity(Long activityId, Long stuId) {
        // 1. 获取活动信息
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null || activity.getDeleted() == 1) {
            return Result.buildFail(20001, "活动不存在");
        }

        // 2. 检查活动是否未开始（状态1-未开始 或 2-报名中）
        if (!isActivityAvailableForApply(activity)) {
            return Result.buildFail(20002, "活动已开始或已结束，无法报名");
        }

        // 3. 检查报名时间（如果设置了报名时间段）
        if (!isWithinSignupPeriod(activity)) {
            return Result.buildFail(20003, "不在报名时间段内");
        }

        // 4. 检查活动容量
        if (isActivityFull(activity)) {
            return Result.buildFail(20004, "活动名额已满");
        }

        // 5. 检查现有报名记录（查询最新的一条记录）
        ActivityCheck existingApplication = activityCheckMapper.selectByActivityAndStudent(
                activityId, stuId);

        if (existingApplication != null) {
            // 记录已被逻辑删除（之前取消过），可以重新激活
            if (existingApplication.getDeleted() != null && existingApplication.getDeleted() == 1) {
                existingApplication.setDeleted(0);
                existingApplication.setStatus(0); // 重置为待审核
                existingApplication.setRemark(null);
                activityCheckMapper.updateById(existingApplication);
                return Result.buildSuccess("报名成功，等待审核");
            }
            // 记录未被删除，检查状态
            if (existingApplication.getDeleted() == null || existingApplication.getDeleted() == 0) {
                // 审核通过的不能重复报名
                if (existingApplication.getStatus() == 1) {
                    return Result.buildFail(20005, "您已通过审核，无需重复报名");
                }
                // 待审核的不能重复报名
                if (existingApplication.getStatus() == 0) {
                    return Result.buildFail(20006, "您已报名，等待审核中");
                }
                // 审核不通过的可以重新报名（更新状态）
                if (existingApplication.getStatus() == 2) {
                    existingApplication.setStatus(0); // 重新设为待审核
                    existingApplication.setRemark(null); // 清空之前的审核意见
                    activityCheckMapper.updateById(existingApplication);
                    return Result.buildSuccess("重新报名成功，等待审核");
                }
            }
        }

        // 6. 全新的报名，创建新记录
        ActivityCheck check = new ActivityCheck();
        check.setActivityId(activityId);
        check.setStudentId(stuId);
        check.setEmployeeId(activity.getEmployeeId()); // 活动创建人作为默认审核人
        check.setStatus(0); // 待审核

        int result = activityCheckMapper.insert(check);
        if (result > 0) {
            return Result.buildSuccess("报名成功，等待管理员审核");
        } else {
            return Result.buildFail(20007, "报名失败，请稍后重试");
        }
    }


    /**
     * 取消报名
     * 只能取消待审核的报名
     */
    @Transactional(rollbackFor = Exception.class)
    public Result cancelApplication(Long activityId, Long studentId) {

        // 1. 获取活动信息
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null || activity.getDeleted() == 1) {
            return Result.buildFail(20001, "活动不存在");
        }

        // 2. 检查活动是否未开始
        if (!isActivityAvailableForApply(activity)) {
            return Result.buildFail(20002, "活动已开始或已结束，无法取消报名");
        }

        // 3. 查找学生的报名记录（获取最新的记录）
        ActivityCheck application = activityCheckMapper.selectByActivityAndStudent(activityId, studentId);

        if (application == null) {
            return Result.buildFail(20003, "未找到报名记录");
        }

        // 4. 检查记录是否已被删除
        if (application.getDeleted() != null && application.getDeleted() == 1) {
            return Result.buildFail(20004, "报名已取消，无需重复操作");
        }

        // 5. 检查报名状态，只能取消待审核或审核不通过的报名
        if (application.getStatus() == 1) {
            return Result.buildFail(20005, "审核已通过，无法取消报名");
        }

        // 6. 逻辑删除（待审核和审核不通过都可以取消）
        application.setDeleted(1);
        int result = activityCheckMapper.updateById(application);

        if (result > 0) {
            return Result.buildSuccess("取消报名成功");
        } else {
            return Result.buildFail(20006, "取消报名失败，请稍后重试");
        }
    }

    /**
     * 获取报名状态详情
     */
    public Result getApplicationStatus(Long activityId, Long studentId) {
        ActivityCheck application = activityCheckMapper.selectByActivityAndStudent(
                activityId, studentId);

        Map<String, Object> result = new HashMap<>();

        // 如果没有报名记录，或者记录已被逻辑删除，视为未报名
        if (application == null || (application.getDeleted() != null && application.getDeleted() == 1)) {
            result.put("hasApplied", false);
            result.put("canApply", true);
            result.put("status", -1);
            result.put("statusText", "未报名");
            result.put("isDeleted", application != null ? application.getDeleted() : null);
        } else {
            // 有有效的报名记录（is_deleted=0）
            result.put("hasApplied", true);
            result.put("applicationId", application.getId());
            result.put("status", application.getStatus());
            result.put("statusText", getStatusText(application.getStatus()));
            result.put("applyTime", application.getCreateTime());
            result.put("updateTime", application.getUpdateTime());
            result.put("isDeleted", application.getDeleted());
            result.put("remark", application.getRemark());

            // 是否可以取消报名（只有待审核状态才能取消）
            boolean canCancel = application.getStatus() == 0;
            result.put("canCancel", canCancel);

            // 是否可以重新报名
            boolean canReapply = application.getStatus() == 2;
            result.put("canReapply", canReapply);
        }

        return Result.buildSuccess(result);
    }

    /**
     * 检查活动是否可用于报名/取消
     */
    private boolean isActivityAvailableForApply(Activity activity) {
        // 活动状态：1-未开始，2-报名中，3-进行中，4-已结束，5-已取消
        return activity.getStatus() == 1 || activity.getStatus() == 2;
    }

    /**
     * 检查是否在报名时间段内
     */
    private boolean isWithinSignupPeriod(Activity activity) {
        LocalDate now = LocalDate.now();

        // 如果没有设置报名时间，则一直可报名
        if (activity.getSignupStartTime() == null && activity.getSignupEndTime() == null) {
            return true;
        }

        // 检查报名开始时间
        if (activity.getSignupStartTime() != null && now.isBefore(activity.getSignupStartTime())) {
            return false;
        }

        // 检查报名结束时间
        if (activity.getSignupEndTime() != null && now.isAfter(activity.getSignupEndTime())) {
            return false;
        }

        return true;
    }

    /**
     * 检查活动是否已满
     */
    private boolean isActivityFull(Activity activity) {
        return activity.getCapacity() != null &&
                activity.getCurrentParticipants() >= activity.getCapacity();
    }

    private String getStatusText(Integer status) {
        switch (status) {
            case 0:
                return "待审核";
            case 1:
                return "审核通过";
            case 2:
                return "审核不通过";
            default:
                return "未知状态";
        }
    }
}


